package juc.cas;

/**
 * @author fangbin
 * @desc模拟CAS操作，等价代码
 * @date 2020/6/16 19:30
 */
public class SimulatedCAS implements Runnable{

    private volatile int value;
    public synchronized int compareAndSwap(int expectedValue,int newValue){
        int oldValue = value;
        if(oldValue==expectedValue){
            System.out.println(Thread.currentThread().getName()+"修改成功");
            value = newValue;
        }
        return  oldValue;
    }

    @Override
    public void run() {
        compareAndSwap(0,1);
    }

    public static void main(String[] args) throws InterruptedException {
        SimulatedCAS simulatedCAS = new SimulatedCAS();
        Thread t1 = new Thread(simulatedCAS);
        Thread t2 = new Thread(simulatedCAS);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(simulatedCAS.value);

    }
}
